var express = require('express');
var router = express.Router();
var pool = require('../config/mysqlconfig');
const jwt = require('jsonwebtoken');

router.post('/signup',function(req,res){
    let username = req.body.username;
    let password = req.body.password;
    pool.getConnection(function(err,conn){
        if(err){
            console.log(err)
        }else{
            console.log("数据库连接成功");
            let data = [username,password];
            let sql ="select * from admin where username=? and password=?";
            conn.query(sql,data,function(error,results){
                if(error){
                    return error
                    
                }
                if(results.length!=0){
                    
                    const payload = {
                        name:results.username
                    }
                    const secret = "deyun"                  
                    const token = jwt.sign(payload,secret,{
                        expiresIn:'10s'});                  
                    res.json({
                        result: results[0],
                        success:true,
                        message:"Enjoy your token",
                        token:token
                    })
                    
                    
                    // console.log(results[0].email)
                }   
                // res.send(results)
                
                conn.release();//shi'fang'shu'ju'ku'li'an
            })
        }
    })
})

router.post('/add',function(req,res){
    pool.getConnection(function(err,conn){
        if(err){
            console.log("数据库连接失败")
        }else{
            let username = req.body.username;
            let passwords = req.body.password;
            let sql = "insert into admin set ?"
            let data={
                username:username,
                password:passwords
            }
            conn.query(sql,data,function(error,results){
                if(error){
                    console.log(error)
                    return
                }
                res.send(results)
                conn.release()
            })
        }
    })
})

module.exports = router